package cn.javacart.jopencart.handler;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.imgscalr.Scalr;

import cn.javacart.jopencart.tools.StrTool;

import com.jfinal.handler.Handler;
import com.jfinal.kit.PathKit;

/**
 * 
 * 图片缩放
 * 格式为 http://xxxx/xxx_320（宽）x240（高）.png
 * @author farmer
 */
public class ImageScalrHandler extends Handler {
	
	@Override
	public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
		Pattern p = Pattern.compile("^.*\\_(\\d+)x(\\d+)(\\.png|\\.jpg|\\.gif|\\.PNG|\\.JPG|\\.GIF)$");
		Matcher m = p.matcher(target);
		OutputStream out = null;
		if (m.matches()) {
			try {
				int w = Integer.parseInt(m.group(1));
				int h = Integer.parseInt(m.group(2));
				if(w*h != 0){
					String file = StrTool.decode(target.replaceAll("\\_(\\d+)x(\\d+)(\\.png|\\.jpg|\\.gif|\\.PNG|\\.JPG|\\.GIF)", "$3"));
					if(new File(PathKit.getWebRootPath(), file).exists()){
						BufferedImage srcImg = Scalr.resize(ImageIO.read(new File(PathKit.getWebRootPath(), file)), Scalr.Method.AUTOMATIC, w , h,Scalr.OP_ANTIALIAS);
						BufferedImage distImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
						Graphics g = distImg.getGraphics();
						g.setColor(Color.WHITE);
						g.fillRect(0, 0, w, h);
						int width = srcImg.getWidth();
						int height = srcImg.getHeight();
						g.drawImage(srcImg, (w - width) / 2, (h - height) / 2, null);
						g.dispose();
						out = response.getOutputStream();
						ImageIO.write(distImg, "PNG", out);
						isHandled[0] = true;
						return;
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				if(out != null){
					try {
						out.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				
			}
		}
		next.handle(target, request, response, isHandled);
	}
}